package Tesk83;

import java.util.Scanner;



public class TEST {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] numbers = null;
        while (true) {
            // 输入数组的大小
            System.out.println("请输入数组的大小: ");
            int size = scanner.nextInt();

            // 输入有序的整数数组
            numbers = new int[size];
            System.out.println("请输入一个升序排列的有序整数数组: ");
            for (int i = 0; i < size; i++) {
             numbers[i] = scanner.nextInt();
            }
              if (isSorted(numbers)) {
                break;
            }
        }
        // 输入目标值
        System.out.println("请输入要查找的目标值: ");
        int target = scanner.nextInt();
        // 调用二分查找方法
        int result = binarySearch(numbers, target);
        // 输出查找结果
        if (result == -1) {
            System.out.println("未找到目标值 " + target);
        } else {
            System.out.println("目标值 " + target + " 在数组中的索引位置为: " + result);
        }
    }
        // 二分查找算法实现
        public static int binarySearch(int[] arr, int target) {
        int min = 0;
        int max = arr.length - 1;
        int mid = min+(max - min) / 2;
        while (min <= max) {
            if (arr[mid]==target){
                return mid;
            }
            else if (arr[mid]>target){
                max = mid-1;
            }

        }
        return -1;
    }
    //判断数组是否升序
    public static Boolean isSorted(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i+1]) {
                return false;
            }
        }
        return true;
    }
}
